package com.cloudkinto.service.quote.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.entity.CompanyDo;
import com.cloudkinto.entity.DimensDo;
import com.cloudkinto.entity.QuotePriceDo;
import com.cloudkinto.dao.QuotePriceDao;
import com.cloudkinto.service.company.CompanyService;
import com.cloudkinto.service.quote.QuotePriceItemService;
import com.cloudkinto.service.quote.QuotePriceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.quote.vo.QuotePriceRes;
import com.cloudkinto.service.shipprice.DimensService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  service实现类
 * </p>
 * @author hua
 * @since 2024-03-23
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class QuotePriceServiceImpl extends ServiceImpl<QuotePriceDao, QuotePriceDo> implements QuotePriceService {
    @Autowired
    private QuotePriceDao dao;
    @Autowired
    private DimensService dimensService;
    @Autowired
    private QuotePriceItemService quotePriceItemService;

    @Autowired
    private CompanyService companyService;

    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }

    @Override
    public Object add(Object req, Long userId) {
        QuotePriceDo entityDo = new QuotePriceDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);
        return handlerAddAfter(entityDo);
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(QuotePriceDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(QuotePriceDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success("");
    }

    @Override
    public Object update(Object req, Long userId) {
        /*QuotePriceDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return handlerUpdateAfter(entityDo);*/
        return null;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(QuotePriceDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(QuotePriceDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        QuotePriceDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(QuotePriceDo entityDo, Long userId) {

    }

    @Override
    public Object detail(Long id) {
        QuotePriceDo entityDo =  dao.selectById(id);
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return handlerDetailAfter(res);
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<Object> getList(Map<String, String> map) {
        QueryWrapper<QuotePriceDo> wrapper = queryBuild(map);
        List<QuotePriceDo> list = this.list(wrapper);
        List<Object> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<QuotePriceDo> wrapper = queryBuild(map);
        IPage<QuotePriceDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<Object> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int)page.getCurrent(), (int)page.getSize(), (int)page.getTotal(), (int)page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<Object> handlerListAfter(List<QuotePriceDo> list ){
        List<Object> result = new ArrayList<>();
        return result;
    }

    private IPage<QuotePriceDo> pageInit(Map<String, String> map) {
        IPage<QuotePriceDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<QuotePriceDo> queryBuild(Map<String, String> map) {
        QueryWrapper<QuotePriceDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("keyword", map.get("keyword"));
        }
        return wrapper;
    }
    /**
     * 根据三边和 重量 快递方式 获取报价
     */
    @Override
    public QuotePriceRes getDoorPrice(Long stateId, double[] size, Long storageId, Long trackId, Long companyId) {
        QuotePriceRes res = new QuotePriceRes(stateId, trackId, storageId);

        if (StaticDict.Track_Type.XinongExpress.getValue().equals(trackId)) {
            res.setPrice(0d);
            res.setMsg("西农手动录入报价");
            return res;
        }
        //看有没有合适的尺寸
        List<DimensDo> dimensDos = dimensService.listBySizeAndWeight(size[3], size[0], size[1], size[2], -2, null, storageId, trackId, null, null, null);
        if (dimensDos.size() == 0) {
            res.setCode(500);
            res.setMsg("尺寸未匹配");
            return res;
        }
        //先看有没有特殊报价
        Long quoteId = this.getEndSpecialQuoteId(companyId, "door");
        if (quoteId == null) {
            //说明没有特殊标价 获取基础报价
            quoteId = this.getBasicQuoteId(companyId, "door");
        }
        if (quoteId == null) {
            res.setCode(500);
            res.setMsg("未匹配报价");
            return res;
        }
        Double price = quotePriceItemService.getPriceItem(quoteId, stateId, dimensDos.get(0).getId());
        if (price == null) {
            res.setCode(500);
            res.setMsg("未匹配报价");
            return res;
        }

        res.setPrice(price);
        res.setQuoteId(quoteId);

        return res;
    }

    public Long getEndSpecialQuoteId(Long companyId, String model) {
        QuotePriceDo quoteDo = dao.selectOne(new LambdaQueryWrapper<QuotePriceDo>().eq(QuotePriceDo::getType, "specialEndQuote").eq(QuotePriceDo::getModel, model)
                .eq(QuotePriceDo::getCompanyId, companyId));
        if (quoteDo == null) {
            return null;
        }
        else {
            return quoteDo.getId();
        }
    }


    /**
     * 根据公司获取基础报价id
     * @param companyId
     * @param model
     * @return
     */
    public Long getBasicQuoteId(Long companyId, String model) {
        CompanyDo companyDo = companyService.getById(companyId);
        if (companyDo == null) {
            return null;
        }
        QuotePriceDo quotePriceDo = dao.selectById(companyDo.getDoorQuoteId());

        return quotePriceDo == null || !"door".equals(quotePriceDo.getModel()) ? null : quotePriceDo.getId();
    }

}
